package com.trytech.mongoocrawler.server;

import com.trytech.mongoocrawler.server.transport.handler.CommandProtocolHandler;
import com.trytech.mongoocrawler.server.transport.handler.HtmltextProtocolHandler;
import com.trytech.mongoocrawler.server.transport.handler.MonitorProtocolHandler;
import com.trytech.mongoocrawler.server.transport.tcp.NettyTcpServer;
import com.trytech.mongoocrawler.server.xml.CrawlerXmlConfigBean;

/**
 * Created by coliza on 2018/4/30.
 */
public final class DistributedCrawlerContext extends CrawlerContext {
    @Override
    protected void doInitSession() {
        //根据配置初始化不同的session
        for (CrawlerXmlConfigBean crawlerXmlConfigBean : config.getConfigBean().getCrawlers().values()) {
            DistributedCrawlerSession initSession = null;
            //注册初始session
            initSession = new DistributedCrawlerSession(this, crawlerXmlConfigBean);
            crawlerXmlConfigBean.getPipeline().setCrawlerSession(initSession);
//            String startUrl = crawlerXmlConfigBean.getStartUrl();
//            HtmlParser htmlParser = crawlerXmlConfigBean.getFirstparser();
            //initSession.pushUrl(new UrlParserPair(startUrl, htmlParser));
            registerSession(initSession);
        }
    }

    @Override
    protected void doInitServer() {
        //启动爬虫server
        crawlerServer = new NettyTcpServer(this, config, config.getConfigBean().getModeConfigBean().getServerPort());
        //初始化ProtocolHandler链
        crawlerServer.addHandler(new CommandProtocolHandler(this));
        crawlerServer.addHandler(new HtmltextProtocolHandler(this));
        crawlerServer.addHandler(new MonitorProtocolHandler(this));
        crawlerServer.start();
    }
}
